<?php

require_once 'common.php';

if (!$_SESSION['admin_id']) {
    die(header('location:login.php'));
}

$case_list_id = $_REQUEST['case_list_id'];

$act = isset($_REQUEST['act']) && !empty($_REQUEST['act']) ? $_REQUEST['act'] : '';

$caseListRow = M('case_list')->where('case_list_id = ' . $case_list_id)->find();

$messageList = M('message_list')
    ->where('case_list_id = ' . $_REQUEST['case_list_id'])
    ->order('create_time asc')->select();

if ($act == 'submitFangan') {
    if ($caseListRow['status'] == 3) {
        returnJson(1, '方案已完结，无需重复提交！');
    }
    $messageListData = array(
        'case_list_id' => $case_list_id,
        'message' => '方案已完结',
        'create_time' => time(),
        'admin_id' => $_SESSION['admin_id'],
        'admin_role' => $_SESSION['admin_role'],
    );
    M('case_list')->where('case_list_id = ' . $case_list_id)->update(array(
        'last_time' => time(),
        'status' => 3
    ));
    M('message_list')->insert($messageListData);
    returnJson(0, '成功');
}

if ($act == 'resetFangan') {
    if ($caseListRow['status'] == 0) {
        returnJson(1, '方案已重置，无需重复提交！');
    }
    M('message_list')->where('case_list_id = ' . $case_list_id)->delete();
    M('case_list')->where('case_list_id = ' . $case_list_id)->update(array(
        'last_time' => time(),
        'status' => 0
    ));
    returnJson(0, '成功');
}

if ($act == 'saveDo') {
    if (count($messageList) < 1 && $_SESSION['admin_role'] == 2) {
        returnJson(1, '请先等待医生给出方案！');
    }
    if ($caseListRow['status'] == 3) {
        returnJson(1, '方案已完结！');
    }
    $messageListData = array(
        'case_list_id' => $case_list_id,
        'message' => $_REQUEST['message'],
        'create_time' => time(),
        'admin_id' => $_SESSION['admin_id'],
        'admin_role' => $_SESSION['admin_role'],
    );
    if (count($messageList) < 1) {
        M('case_list')->where('case_list_id = ' . $case_list_id)->update(array(
            'last_time' => time(),
            'status' => 1
        ));
    }
    if ($_SESSION['admin_role'] == 1) {
        M('case_list')->where('case_list_id = ' . $case_list_id)->update(array(
            'last_time' => time(),
            'status' => 1
        ));
    }
    if ($_SESSION['admin_role'] == 2) {
        M('case_list')->where('case_list_id = ' . $case_list_id)->update(array(
            'last_time' => time(),
            'status' => 2
        ));
    }
    M('message_list')->insert($messageListData);
    returnJson(0, '成功');
}

foreach ($messageList as $key => $value) {
    $adminRow = M('admin')->where('admin_id = ' . $value['admin_id'])->find();
    $value['username'] = $adminRow['username'];
    $messageList[$key] = $value;
}

display('schemeList');